import {login, logout, getInfo, getAllAdmin, addNewAdmin, delSocietyAdmin} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    type: '',
    society_id:null,
    societyAdmins: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_TYPE: (state, type) => {
    state.type = type
  },
  SET_SOCIETYID: (state, id) => {
    state.society_id = id
  },
  SET_SOCIETYADMIN: (state, data) => {
    state.societyAdmins = data
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const {data} = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {data} = response

        if (!data) {
          return reject('登录失败, 请重新登录')
        }

        const {name, avatar, type,society_id} = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_TYPE', type)
        commit('SET_SOCIETYID',society_id)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // 获取首页社团管理员信息
  async getAllSocietyAdmins({commit}, {pageNo, limit}) {
    let result = await getAllAdmin(pageNo, limit);
    if (result.code === 200) {
      commit('SET_SOCIETYADMIN', result.data.adminsInfo)
    }
  },

  // 添加社团管理员
  async addSocietyAdmin(_, societyId) {
    let result = await addNewAdmin(societyId);
    if (result.code === 200) {
      return "OK"
    }
  },

  // 删除社团管理员
  async deleteSocietyAdmin({commit}, ids) {
    let res = await delSocietyAdmin(ids);
    if (res.code === 200) {
      return 'OK'
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

